package com.example.iot;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;

import androidx.annotation.NonNull;

public class NetworkStateReceiver {
    private static ConnectivityManager connectivityManager;

    public static boolean isConnected(Context context) {
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

        return (activeNetworkInfo != null) && activeNetworkInfo.isConnectedOrConnecting();
    }

    public void setNetworkStateListener(NetworkStateListener listener) {
        connectivityManager.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                listener.onNetworkConnected();
            }

            @Override
            public void onLost(@NonNull Network network) {
                listener.onNetworkDisconnected();
            }
        });
    }
}
